package com.qf.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.openapi2204.common.constants.RedisConstants;
import com.qf.openapi2204.common.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class ParamFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        //1. 获取redis中设置好的必传参数 set
        List<String> paramList = new ArrayList<String>();

        paramList.add("costomerkey");
        paramList.add("apiname");
        paramList.add("sign");

        //2. 校验请求中的参数是不是齐全
        RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();

        Set<String> reuqestParamSet = request.getParameterMap().keySet();

        // 集合的减法
        paramList.removeAll(reuqestParamSet);

        // 如果paramList中还有剩余元素，则说明必传参数没有都传
        if (paramList.size()>0){
            // 请求到此结束，不要在往后面的微服务发送了
            currentContext.setSendZuulResponse(false);

            HttpServletResponse response = currentContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            try {
                response.getWriter().println("请求参数缺少了，请检查"+paramList);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return null;
    }
}
